//商品js模块定义 by sanm 2017-5-12 14:53:12.
define(['jquery'],function($){
    var appUrl = $('#_ctx').val();

    //商品select
    var sku = {
        //二级分类
        changeTop:function(id){
            id && $("#categoryId").val(id);
            $.ajax({
                type: "get",
                url: appUrl+'/outdoor/category/categoryNextList?pid=' + id,
                data: {pid: id},
                dataType: 'json',
                success: function (data) {
                    var cityhtml = "<option value=''>请选择二级分类</option>";
                    var level_2 = $("#level_2").val();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if(data[i].id == level_2){
                                cityhtml = cityhtml + ("<option  value=" + data[i].id + " selected>" + data[i].name + "<\/option>");
                            }
                            else{
                                cityhtml = cityhtml + ("<option  value=" + data[i].id + ">" + data[i].name + "<\/option>");
                            }
                        }
                        $("#sec").html(cityhtml);
                        console.log(level_2)
                        if(!level_2){
                            $("#third").html("<option value=''>请选择三级分类</option>");
                            $("#four").html("<option value=''>请选择四级分类</option>");
                        }
                    } else {
                        $("#sec").html(cityhtml);
                        $("#third").html("<option value=''>请选择三级分类</option>");
                        $("#four").html("<option value=''>请选择四级分类</option>");
                    }
                }
            });
        },
        //三级分类
        changeSec:function(id){
            id && $("#categoryId").val(id);
            $.ajax({
                type: "get",
                url: appUrl+'/outdoor/category/categoryNextList?pid=' + id,
                data: {pid: id},
                dataType: 'json',
                success: function (data) {
                    var areahtml = "<option value=''>请选择三级分类</option>";
                    var level_3 = $("#level_3").val();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if(data[i].id == level_3){
                                areahtml = areahtml + ("<option value=" + data[i].id + " selected>" + data[i].name + "<\/option>");
                            }
                            else{
                                areahtml = areahtml + ("<option value=" + data[i].id + ">" + data[i].name + "<\/option>");
                            }
                        }
                        $("#third").html(areahtml);
                        if(!level_3) {
                            $("#four").html("<option value=''>请选择四级分类</option>");
                        }
                    } else {
                        $("#third").html(areahtml);
                        $("#four").html("<option value=''>请选择四级分类</option>");
                    }
                }
            });
        },
        //四级分类
        changeThird:function(id){
            id && $("#categoryId").val(id);
            $.ajax({
                type: "get",
                url: appUrl+'/outdoor/category/categoryNextList?pid=' + id,
                data: {pid: id},
                dataType: 'json',
                success: function (data) {
                    var areahtml = "<option value=''>请选择四级分类</option>";
                    var level_4 = $("#level_4").val();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if(data[i].id == level_4){
                                areahtml = areahtml + ("<option value=" + data[i].id + " selected>" + data[i].name + "<\/option>");
                            }
                            else{
                                areahtml = areahtml + ("<option value=" + data[i].id + ">" + data[i].name + "<\/option>");
                            }
                        }
                        $("#four").html(areahtml);
                    } else {
                        $("#four").html(areahtml);
                    }
                }
            });
        },
        changeBrand:function(value){
            $("#brandId").val(value);
        },
        setName:function(obj){
            $('#feeTemplateName').val($("#feeTemplate_" +$(obj).val()).html());
        }
    };

    //数组重组方法
    var arrChange = function(doubleArrays) {
        var len = doubleArrays.length;
        if (len >= 2) {
            var arr1 = doubleArrays[0];
            var arr2 = doubleArrays[1];
            var len1 = doubleArrays[0].length;
            var len2 = doubleArrays[1].length;
            var newlen = len1 * len2;
            var temp = new Array(newlen);
            var index = 0;
            for (var i = 0; i < len1; i++) {
                for (var j = 0; j < len2; j++) {
                    temp[index] = arr1[i] + "," + arr2[j];
                    index++;
                }
            }
            var newArray = new Array(len - 1);
            newArray[0] = temp;
            if (len > 2) {
                var _count = 1;
                for (var i = 2; i < len; i++) {
                    newArray[_count] = doubleArrays[i];
                    _count++;
                }
            }
            return arrChange(newArray);
        }
        else {
            return doubleArrays[0];
        }
    };

    //上传图片
    var flag = false;//flag是否多张
    var uploadImg = function(obj,flag){
        //创建FormData对象
        var data = new FormData();
        var at = $(obj).attr("data-image");
        var action = $(obj).attr("data-action");
        //为FormData对象添加数据
        data.append('image', $(obj)[0].files[0]);

        //判定图片大小和尺寸
        if(getPhotoSize(obj,3)){
            var objUrl = getObjectURL(obj.files[0]);
            getImageWidth(objUrl, function(w, h) {
                var size = "?" + w + "/" + h;
                if (w > 1000) {
                    alert("图片尺寸太大，请处理成建议尺寸");
                    return false;
                }
                else {
                    $.ajax({
                        url: appUrl + '/upload/' + action,
                        type: 'POST',
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            //获取图片尺寸
                            res = res + size;

                            //多图
                            if (flag) {
                                $(obj).before("<div class='detail-box'>" +
                                    "<input type='hidden' name=" + at + " value=" + res + "  />" +
                                    "<img class='test' src=" + res + " />" +
                                    "<i class='fa fa-close'></i></div>");
                                //删除
                                $(".detail-box i").click(function () {
                                    var detBox = $(this).parent();
                                    $.ajax({
                                        url: appUrl + '/upload/remove',
                                        type: "POST",
                                        data: JSON.stringify({'name': res, 'id': 0}),
                                        dataType: "json",
                                        contentType: "application/json; charset=utf-8",
                                        success: function (res) {
                                            console.log(res);
                                            detBox.remove();
                                        }
                                    });
                                });
                            }
                            //单图
                            else {
                                var _this = $(obj).parent();
                                _this.hide();
                                //预先取消绑定 -- 兼容webkit
                                _this.siblings(".obj-img").off("click");
                                _this.siblings(".obj-img").attr("src", res).show().on("click", function () {
                                    $(obj).click();
                                });
                                _this.siblings(".obj-input").val(res);
                                _this.siblings("input.old-val").val(res);
                            }

                        }
                    });
                }
            })
        }
        //获取图片原始尺寸方法
        function getImageWidth(url,callback){
            var img = new Image();
            img.src = url;
            // 如果图片被缓存，则直接返回缓存数据
            if(img.complete){
                callback(img.width, img.height);
            }
            // 完全加载完毕的事件
            else{
                img.onload = function(){
                    callback(img.width, img.height);
                }
            }
        }
        //判断图片大小
        function getPhotoSize(obj,imgSize){
            var photoExt = obj.value.substring(obj.value.lastIndexOf(".")+1).toLowerCase();//获得文件后缀名
            if(photoExt!='jpg'&&photoExt!='jpeg'&&photoExt!='bmp'&&photoExt!='png'){
                alert("图片格式必须是.jpg/.jpeg/.bmp/.png!");
                return false;
            }
            var imgSize = imgSize || 3;
            var fileSize = 0;
            var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
            if (isIE && !obj.files) {
                var filePath = obj.value;
                var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                var file = fileSystem.GetFile (filePath);
                fileSize = file.Size;
            }else {
                fileSize = obj.files[0].size;
            }
            fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
            if(fileSize>imgSize*1024){
                alert("图片最大为"+imgSize+"M，请重新上传!");
                return false;
            }
            return fileSize;
        }
        //获取图片临时url -- 1.判断图片尺寸 2.可实现预览
        function getObjectURL(file) {
            var url = null ;
            if (window.createObjectURL!=undefined) { // basic
                url = window.createObjectURL(file) ;
            } else if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        }
    };



    // //加法
    // var add = function(x,y){
    //     return x+y;
    // };

    //返回调用方法
    return {
        sku: sku,
        arrChange: arrChange,
        uploadImg: uploadImg

    };
});